package com.demo.seckill.distributedlock.zookeeper;

import java.util.concurrent.TimeUnit;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author libo
 * @ClassName ZkLockUtil
 * @Description: zk 实现的分布式锁
 * @date 2018/11/16 18:19
 */
public class ZkLockUtil {
    private static String ZK_ADDRESS = "10.130.13.56:2181";
    private static CuratorFramework curatorFramework;
    //静态代码初始化
    static {
        try{
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
            curatorFramework = CuratorFrameworkFactory.newClient(ZK_ADDRESS,retryPolicy);
            curatorFramework.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private ZkLockUtil(){ }

    private static class SingletonHolder{
        private static InterProcessMutex mutex = new InterProcessMutex(curatorFramework,"/curator/lock");
    }

    public static InterProcessMutex getMutex(){
        return  SingletonHolder.mutex;
    }

    //获得了锁
    public static boolean acquire(long time, TimeUnit unit){
        try {
            return getMutex().acquire(time,unit);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //释放锁
    public static void release(){
        try {
            getMutex().release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        boolean res = ZkLockUtil.acquire(10,TimeUnit.SECONDS);
        System.out.println(res);
    }
}
